import { baseURL } from '@/api/_client.ts';
import { getProjectDynamic } from '@/api/agriculture.ts';
import { defineStore } from 'pinia';
import { computed, ref } from 'vue';

export const useProjectStore = defineStore('ProjectStore', () => {
  const projectData = ref<any[]>([]);
  const loading = ref<boolean>(false);
  const projectPage = ref({
    currentPage: 1,
    total: 0,
    pageSize: 10,
    showSizePicker: true,
    pageSizes: Array.from({ length: 200 }, (_, index) => index + 1),
  });

  const updateProjectData = async () => {
    loading.value = true;
    const req = {
      pageNo: projectPage.value.currentPage,
      pageSize: projectPage.value.pageSize,
    };

    const res = await getProjectDynamic(req);
    const { data, meta } = res;

    projectData.value = data.map((item: any) => ({
      id: item.id,
      title: item.attributes.title,
      image: baseURL + `${item.attributes.image.data.attributes.url}`,
      date: item.attributes.time,
      content: item.attributes.information,
    }));
    projectPage.value.total = meta.pagination.total;
    loading.value = false;
  };

  // 设置分页信息
  const setProjectPage = (page?: number) => {
    if (page) projectPage.value.currentPage = page;
  };

  const getProjectData = computed(() => {
    return projectData.value;
  });

  const getProjectPage = computed(() => {
    return projectPage.value;
  });

  const pagination = computed(() => ({
    current: projectPage.value.currentPage,
    total: projectPage.value.total,
    pageSize: projectPage.value.pageSize,
    onChange: (page: number) => {
      setProjectPage(page);
      updateProjectData().then();
    },
  }));

  const getProjectLoading = computed(() => {
    return loading.value;
  });

  return {
    updateProjectData,
    getProjectData,
    projectPage,
    setProjectPage,
    getProjectPage,
    pagination,
    getProjectLoading,
  };
});
